package com.lizi.idgenerator.utils;

import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.ValidationException;
import javax.validation.Validator;
import org.springframework.util.CollectionUtils;

/**
 * 模型校验器
 * @author kingman
 * @since 2020-12-15 15:25
 */
public class ModelValidator {
    public ModelValidator() {
    }

    public static <T> void validate(T object) {
        Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
        Set<ConstraintViolation<T>> constraintViolations = validator.validate(object, new Class[0]);
        if (!CollectionUtils.isEmpty(constraintViolations)) {
            throw new ValidationException(convertErrorMsg(constraintViolations));
        }
    }

    private static <T> String convertErrorMsg(Set<ConstraintViolation<T>> set) {
        Map<String, StringBuilder> errorMap = new HashMap();
        Iterator var3 = set.iterator();

        while(var3.hasNext()) {
            ConstraintViolation<T> cv = (ConstraintViolation)var3.next();
            String property = cv.getPropertyPath().toString();
            if (errorMap.get(property) != null) {
                ((StringBuilder)errorMap.get(property)).append("," + cv.getMessage());
            } else {
                StringBuilder sb = new StringBuilder();
                sb.append(cv.getMessage());
                errorMap.put(property, sb);
            }
        }

        return errorMap.toString();
    }
}
